package com.example.springboot.utils;

import com.example.springboot.common.MinioConfig;
import com.example.springboot.exception.FileUploadException;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
@AllArgsConstructor
@Slf4j
public class FileUtil {

    private final MinioConfig minioConfig;
    private final MinioClient minioClient;

    public String upload(MultipartFile file) {
        // 确保 objectArgs 构建正确
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(file.getOriginalFilename())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            throw new FileUploadException("上传文件失败",e);
        }


        log.info("文件上传成功");
        //上传文件后获取url
        String url = null;
        try {
            url = minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(file.getOriginalFilename())
                                .method(Method.GET)
                                .build()
                );
        } catch (Exception e) {
            throw new RuntimeException("获取url失败",e);
        }
        log.info("获取url成功");
        return url;
    }

}
